<?php


namespace app\api\controller;


use app\api\service\OrderService;
use app\common\controller\Api;
use think\Config;
use think\Db;
use app\common\model\Order as OrderModel;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use app\common\model\UserRoll;
use app\common\model\OrderFail;
use fast\Http;
use app\api\service\OcrService;

/**
 * 订单类
 * Class Order
 * @package app\api\controller
 */
class Order extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['meituanRedEnvelope','elemRedEnvelope','meituanList','cancel','shopList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**订单列表
     * @param OrderService $orderService
     * 待上传，已完成，已取消，已超时，待审核，已驳回，已报名待下单
     */
    public function list(OrderService $orderService)
    {
        $page = input('page/d', 1);
        $status = input('status/d', '0');
        $where = 'user_id='.$this->auth->id;
        if ($status!=0) {
            if ($status==1) {
                $where .= ' and order_status in (1,4)';// 4-美团官方活动已下单的状态
            }elseif ($status==2) {
                $where .= ' and order_status in (2,-5,6)';
            }elseif ($status==3) {
                $where .= ' and order_status in (3,-6,-7,-8,-9)';
            }elseif ($status==4) {
                $where .= ' and order_status in (1,-3,4)';
            }else{
                $where .= ' and order_status='.$status;
            }
        }
        $pageSize = 10;
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        $sql = 'select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type,is_pay,actual_rebate_amt,user_pay,update_dt,is_yunzhan,play_no,shop_no,crood_type,pay_time,proposal from chbc_mtofficial_order where '.$where.' order by create_dt DESC limit '.($page-1)*$pageSize.','.$pageSize;
        $data = Db::query($sql);
        $sql = 'select count(*) as count from (select id,create_dt,shop_name,place_time,order_status,expire_time,1 as type from chbc_play_order where '.$where.' union all select id,create_dt,shop_name,place_time,order_status,expire_time,2 as type from chbc_mtofficial_order where '.$where.') a';
        $data2 = Db::query($sql);
        $count = $data2[0]['count'];
        $list = [];
        $playObj = new \app\admin\model\Play();
        foreach ($data as $key => $value) {
            if ($value['type']==1) {
                if ($value['order_status']==1 && $value['expire_time']<time()) {
                    unset($data[$key]);
                    continue;
                }
                $order = OrderModel::where('id',$value['id'])->find();
                $value['play_order_no'] = $order['is_yunzhan']==0?$order['play_order_no']:$order['yunzhan_order_no'];
                $value['poiEventId'] = '';
                if ($order['is_yunzhan']==0) {
                    $play = $playObj->where('play_no',$order['play_no'])->find();
                    $shop = \app\admin\model\Shop::where('shop_no',$order['shop_no'])->find();
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$shop['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                } else {
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $value['poiEventId'] = isset($play['poiEventId'])?$play['poiEventId']:'';
                }
                $value['play'] = [];
                $value['play']['back_money'] = (int)$play['back_money'];
                $value['play']['back_money_text'] = $play['back_money_text'];
                $value['play']['play_type'] = $play['play_type'];
                $value['play']['img_url'] = $play['img_url'];
                $value['play']['scheme_no'] = $play['scheme_no'];
                $value['play']['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$play);
                $value['shop'] = [];
                $value['shop']['shop_name'] = $shop['shop_name'];
                $value['shop']['shop_type_text'] = $shop['shop_type_text'];
                $value['shop']['shop_type'] = isset($shop['shop_type'])?$shop['shop_type']:1;
                $value['shop']['logo_pic_url'] = $shop['logo_pic_url'];
                $value['shop']['is_xls'] = isset($shop_platform['is_xls'])?$shop_platform['is_xls']:0;
                $value['shop']['elm_appenter'] = isset($shop_platform['elm_appenter'])?$shop_platform['elm_appenter']:'';
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id desc')->field('id,one_image,two_image,three_image,platform_no,wm_order_sn,supplement,handle_admin_desc,upload_time')->find();
                if ($value['order_status']==1 && $value['place_time']>0 && !$value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已报名，待下单';
                } elseif ($value['order_status']==1 && $value['place_time']>0 && isset($value['proof']['wm_order_sn']) && $value['proof']['wm_order_sn']) {
                    $value['crood_type'] = '已下单，待反馈';
                } elseif ($value['order_status']==2 || $value['order_status']==-5) {
                    $value['crood_type'] = '待审核';
                } elseif ($value['order_status']==6) {
                    $value['crood_type'] = '待商家复审';
                } elseif ($value['order_status']==-2) {
                    $value['crood_type'] = '超时取消，订单关闭';
                } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                    $value['crood_type'] = '已取消';
                } elseif ($value['order_status']==-3) {
                    $value['crood_type'] = '已驳回';
                } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                    $value['crood_type'] = '已完成';
                }
                $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                // 驳回原因
                if ($value['proof']['handle_admin_desc']) {
                    $explode = explode('（', $value['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $value['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
            } else {
                $order = \app\common\model\Mtorder::where('id',$value['id'])->find();
                if ($order['is_yunzhan']==0) {
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $content = json_decode($order['content'],1);
                    $value['play'] = [];
                    $value['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                    $value['play']['img_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                    $value['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                    $value['play']['scheme_no'] = '';
                    $value['play']['scheme_no_text'] = '';
                    $platform_no = '';
                    if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                        $wxPath = explode('?', $content['actionUrl']['wxPath']);
                        if (isset($wxPath[1]) && $wxPath[1]) {
                            $path = explode('&', $wxPath[1]);
                            foreach ($path as $p) {
                                if (strpos($p,'poi_id=')!==false) {
                                    $platform_no = ltrim($p,'poi_id=');
                                }
                                if (strpos($p,'poi_id_str=')!==false) {
                                    $platform_no .= '&'.$p;
                                }
                            }
                        }
                    }
                    $value['planActivityType'] = 1;
                    if ($order['cps_id'] && $content['poiEventId']!=$order['cps_id'] && isset($content['planActivityInfoList'])) {
                        foreach ($content['planActivityInfoList'] as $valuess) {
                            if ($order['cps_id']==$valuess['poiEventId']) {
                                $value['planActivityType'] = $valuess['planActivityType'];
                                $content['maxCommission'] = $valuess['maxCommission'];
                                $content['ratio'] = $valuess['ratio'];
                            }
                        }
                    }
                    // foreach ($content['planActivityInfoList'] as $valuess) {
                    //     if ($order['cps_id']==$valuess['poiEventId']) {
                    //         $content['maxCommission'] = $valuess['maxCommission'];
                    //         $content['ratio'] = $valuess['ratio'];
                    //     }
                    // }
                    $value['platform_no'] = $platform_no;
                    $value['shop'] = [];
                    $value['shop']['shop_name'] = isset($content['name'])?$content['name']:'';
                    $value['shop']['shop_type_text'] = '美团';
                    $value['shop']['logo_pic_url'] = isset($content['picture'])?$content['picture']:'';
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                    $value['ratio'] = $ratio;
                    $value['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$ratio/10000,2);
                        $maxCommission = floor($value['maxCommission']/100);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } elseif (in_array($order['is_yunzhan'],[4,5])) {
                    $content = isset($order['content'])?json_decode($order['content'],1):[];
                    $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($order['play_no'],$order['cps_id'],$content);
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['scheme_no']-1;
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop_type'] = $play['shop_type'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                        if ($value['order_status']==-4) {
                            $value['proof']['handle_admin_desc'] = '订单实付金额未满足活动要求';
                        }
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round(floatval($value['user_pay'])*floatval($value['ratio'])/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                } else {
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['cps_id'],json_decode($order['content'],1));
                    $value['poiEventId'] = $order['cps_id'];
                    $value['play_order_no'] = $order['play_order_no'];
                    $value['mtofficial'] = 1;
                    $value['play'] = $play;
                    $value['planActivityType'] = $play['planActivityType'];
                    $value['platform_no'] = $shop['platform_no'];
                    $value['shop'] = $shop;
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    $value['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                    if ($order['content']) {
                        $content2 = json_decode($order['content'],1);
                    }
                    if ($value['order_status']==1 && $value['pay_time']==0) {
                        $value['crood_type'] = '已报名，待下单';
                    } elseif ($value['order_status']==1 && $value['pay_time']>0) {
                        $value['crood_type'] = '已下单，待反馈';
                    } elseif ($value['order_status']==4 || $value['order_status']==-5) {
                        if ($value['is_pay']==1) {
                            $value['crood_type'] = '已下单，待完成';
                        } else {
                            $value['crood_type'] = '已下单，待评价';
                        }
                    } elseif ($value['order_status']==-2) {
                        $value['crood_type'] = '超时取消，订单关闭';
                    } elseif ($value['order_status']==-1 || $value['order_status']==-4) {
                        $value['crood_type'] = '已取消';
                    } elseif ($value['order_status']==-3) {
                        $value['crood_type'] = '已驳回';
                    } elseif (in_array($value['order_status'],[3,-6,-7,-8,-9])) {
                        $value['crood_type'] = '已完成';
                    } elseif ($value['order_status']==99) {
                        $value['crood_type'] = '审核中';
                    }
                    $value['expire_time_text'] = date('Y/m/d H:i',$value['expire_time']);
                    $value['update_dt'] = date('Y/m/d H:i',strtotime($value['update_dt']));
                    $value['place_time_text'] = date('m/d H:i',$value['place_time']);
                    // 驳回原因
                    if ($value['proof']['handle_admin_desc']) {
                        $explode = explode('（', $value['proof']['handle_admin_desc']);
                        if (isset($explode[1]) && $explode[1]) {
                            $explode = explode('）', $explode[1]);
                        }
                        if (isset($explode[0])) {
                            $value['proof']['handle_admin_desc'] = $explode[0];
                        }
                    }
                    $value['ratio'] = $play['ratio'];
                    $value['maxCommission'] = $play['maxCommission'];
                    if ($value['user_pay']>0) {
                        $actual_rebate_amt = round($value['user_pay']*$value['ratio']/100,2);
                        $maxCommission = floor($value['maxCommission']);
                        if ($actual_rebate_amt>$maxCommission) {
                            $value['actual_rebate_amt'] = $maxCommission/100;
                        }
                    }
                }
            }
            $value['mobile'] = $order['proposal'];
            $value['source'] = $value['is_yunzhan'];
            $list[] = $value;
        }
        $last_page = ceil($count/$pageSize);
        $this->success('', ['list'=>$list,'last_page'=>$last_page, 'total' => $count]);
    }


    /**
     * 提交单号锁定名额
     * @DateTime 2023-04-02T19:28:35+0800
     * @return   [type]                   [description]
     */
    public function reserve1()
    {
        //外卖单号
        $wm_order_sn = input('wm_order_sn', '','htmlspecialchars,htmlentities');
        $poiEventId = input('poiEventId', '','');
        $wm_order_sn = trim($wm_order_sn);
        $poiEventId = trim($poiEventId);
        $wm_order_sn = str_replace(' ', '', $wm_order_sn);  // 当前平台订单id
        if (!$wm_order_sn) {
            $this->error('请上传正确单号');
        }
        if (!is_numeric($wm_order_sn) || !\think\Validate::is($wm_order_sn, '\S{18,30}')) {
            $this->error('单号格式不对');
        }

        $play_order_no = input('play_order_no', '','htmlspecialchars,htmlentities'); 
        if ($poiEventId && $poiEventId!='undefined' && $poiEventId!='null') {
            $order = OrderModel::where('yunzhan_order_no',$play_order_no)->find();
        } else {
            $order = OrderModel::where('play_order_no',$play_order_no)->find();
        }
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['order_status']!=1) {
            $this->error('订单状态有误');
        }
        // $play = (new \app\admin\model\Play())->where(['play_no' => $order->play_no])->find();
        // if (!$play) {
        //     $this->error('活动不存在');
        // }
        // 是否超过30分钟
        if (time()>$order['expire_time']) {
            $this->error('超过1小时未上传单号，订单已过期');
        }
        // 同一订单号提交过后不可重复提交
        $snNUm = OrderModel::where([
            'wm_order_sn'=>$wm_order_sn,
            'order_status' => ['in',[1,2,3,-3,-5,-6,-7,-8,-9]]
        ])->find();
        if (count($snNUm)>0) {
            $this->error('该外卖单号已使用过');
        }
        Db::startTrans();
        try {
            // $order->expire_time = time()+intval(config('proof_expire')); // 6hour
            $order->expire_time = strtotime(date('Ymd',$order['place_time']))+129600; // 明天中午12
            $order->wm_order_sn = $wm_order_sn;
            $order->save();
            $OrderProof = new OrderProof();
            $data = [
                'wm_order_sn' => $wm_order_sn,
                // 'merchant_id' => $play['user_id'],
                'shop_no' => $order['shop_no'],
                'user_id' => $order['user_id'],
                'play_order_no' => $play_order_no,
                'platform_no' => $order['platform_no'],
                'user_pay' => $order['user_pay'],      // 满多少
                'back_money' => $order['actual_rebate_amt'] //返多少
            ];
            $OrderProof->allowField(true)->save($data);
            // orderlog
            OrderLog::create([
                'play_order_id' => $order['id'],
                // 'play_order_no' => $order['yunzhan_order_no'],
                'create_by' => $this->auth->nickname,
                'create_by_id' => $this->auth->id,
                'is_front' => 1,
                'info' => '提交单号',
            ]);
            if ($poiEventId && $poiEventId!='undefined' && $poiEventId!='null') {
                $bwc = new \services\BwcService();
                $res = $bwc->confirmOrder($play_order_no,$this->auth->mobile,$wm_order_sn);
                // $res = '{"status":true,"code":200,"message":"success","data":true}';
                \think\Log::write('回填单号exception1=>'.$res);
                $decode = json_decode($res,1);
                if ($decode['status']!=true) {
                    $this->error($decode['message']);
                }
            }
            Db::commit();
            $this->success('单号提交成功，请尽快提交下单凭证');
        } catch (Exception $e) {
            \think\Log::write('提交单号：Exception=>'.$e->getMessage(), 'error');
            Db::rollback();
            $this->error('提交单号失败');
        }   
    }


    /**
     * 是否具备下单条件
     * @return [type] [description]
     */
    public function validateOder1()
    {
        $poiEventId = input('poiEventId', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        if ($poiEventId) {
            $play_no = input('id', '');
            //活动检测
            $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
            if (!$user) $this->error('该账号暂不能报名');
            if (!$user->mobile) $this->error('请先绑定手机号');
            list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($play_no,$poiEventId);
            if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                $this->error('无法参与该活动');
            }
            if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
            $userorder = order_count_read($userId);
            if ($userorder<6) {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 2) $this->error('您的报名次数已用完');
            } else {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 5) $this->error('您的报名次数已用完');
            }

            // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => -5
            ])->count();
            if ($orderNum) {
                $this->error('您好，您当前有一笔“我要反馈”订单正在处理中，需等该笔订单完成后才能继续参加返利活动哦~');
            }
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => ['in',[-7,-8]]
            ])->field('play_order_no')->find();
            if ($orderNum) {
                $proof = Db::name('play_order_proof')->where('play_order_no',$orderNum['play_order_no'])->order('id DESC')->value('handle_merchant_desc');
                $handle_merchant_desc = json_decode($proof,1);
                if (isset($handle_merchant_desc['desc'])) {
                    $this->error('宝子，商家反映您目前有一笔订单存在“异常类型：'.$handle_merchant_desc['desc'].'”请联系客服处理完才能继续参与返利活动哦~~');
                } else {
                    $this->error('宝子，商家反映您目前有一笔订单存在异常，请联系客服处理完才能继续参与返利活动哦~~');
                }
            } 
        } else {
            $play_no = input('play_no', '');
            //活动检测
            $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
            if (!$user) $this->error('该账号暂不能报名');
            if (!$user->mobile) $this->error('请先绑定手机号');

            //活动检测
            $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
            if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                $this->error('无法参与该活动');
            }
            if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
            if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
            if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

            $orderNum = (new \app\common\model\Order())->where([
                'user_id' => $userId,
                'shop_no' => $play['shop_no'],
                'order_status' => ['in',[1,2,-3,-5]]
            ])->count();
            if ($orderNum) {
                $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
            }
            // 如果是新用户专享，只能新用户报名
            // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
            $olduser = order_count_read($userId);
            if ($play['play_label']==2 && $olduser) {
                $this->error('您不是新用户，不能报名新用户专享活动');
            }
            // 华东师范大学(中山北路校区) 的新用户限制下单
            // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
            //     $this->error('无法参与该活动');
            // }
            // 是否有大牌专享券
            $play_label = 0;
            $config = config('site.play_label');
            if (count($config)) {
                foreach ($config as $keys => $values) {
                    if ($values=='大牌专享') {
                        $play_label = $keys;
                    }
                }
            }
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            if ($play_label>0 && $play['play_label']==$play_label) {
                $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有大牌专享券，抢单失败';
            } else {
                $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有饭票，抢单失败';
            }
            if (!$roll) {
                $this->error($error);
            }
            // 是否超前抢单
            $roll2 = [];
            if ($is_leading) {
                // 是否在活动开始前30分钟
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                if (time()<$start_time_str && time()>=$start_time_str-1800) {
                    $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                    if (!$roll2) {
                        $this->error('您没有超前抢单券，抢单失败');
                    }
                } else {
                    $this->error('超前抢单券不可用，抢单失败');
                }
            } else {
                // 判断是不是活动时间
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                $end_time_str = strtotime(date('Ymd').' '.$play['end_time_str']);
                if (time()<$start_time_str || time()>$end_time_str) {
                    $this->error('不在活动时间内');
                }
            }
            // 下单限制
            if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
                // 过去几天
                $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['not in', [-1, -2, -4]],
                    'create_dt' => ['>',$thisday]
                ])->count();
                if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
            }
            //下单限制检测，每天只能报名一次
            // $thisday = date('Y-m-d',time());
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'order_status' => ['not in', [-1, -2, -4]],
            //     'create_dt' => ['>',$thisday]
            // ])->count();
            // if ($orderNum >= 1) $this->error('该店铺活动每天只能参加一次哦，试试其他的活动吧~');
            // // 每周只能报名三次
            // $thisweek = time()-86400*7;
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'order_status' => ['not in', [-1, -2, -4]],
            //     'create_dt' => ['>',date('Y-m-d H:i:s',$thisweek)]
            // ])->count();
            // if ($orderNum >= 3) $this->error('该店铺活动每周只能参加三次哦，试试其他的活动吧~');
           
            // 同一个用户同一家店铺两个小时内只能报名一个订单
            // $orderNum = (new \app\common\model\Order())->where([
            //     'user_id' => $userId,
            //     'shop_no' => $play['shop_no'],
            //     'create_dt' => ['>',date('Y-m-d H:i:s',(time()-7200))]
            // ])->count();
            // if ($orderNum >= 1) $this->error('同一个用户同一家店铺两个小时内只能报名一个订单');
            // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
            $userorder = order_count_read($userId);
            if ($userorder<6) {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 2) $this->error('您的报名次数已用完');
            } else {
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'create_dt' => ['>=',date('Y-m-d',time())],
                    'order_status' => ['not in',[-1,-2,-4]]
                ])->count();
                if ($orderNum >= 5) $this->error('您的报名次数已用完');
            }
            // 店铺是否禁止用户下单
            $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
            if ($shop['limited_user']) {
                $limited_user = trim($shop['limited_user'],'|');
                $limited_user_arr = explode('|', $limited_user);
                if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                    $this->error('您已超出该店铺点餐次数上限');
                }
            }

            // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => -5
            ])->count();
            if ($orderNum) {
                $this->error('您好，您当前有一笔“我要反馈”订单正在处理中，需等该笔订单完成后才能继续参加返利活动哦~');
            }
            $orderNum = Db::name('play_order')->where([
                'user_id' => $userId,
                'order_status' => ['in',[-7,-8]]
            ])->field('play_order_no')->find();
            if ($orderNum) {
                $proof = Db::name('play_order_proof')->where('play_order_no',$orderNum['play_order_no'])->order('id DESC')->value('handle_merchant_desc');
                $handle_merchant_desc = json_decode($proof,1);
                if (isset($handle_merchant_desc['desc'])) {
                    $this->error('宝子，商家反映您目前有一笔订单存在“异常类型：'.$handle_merchant_desc['desc'].'”请联系客服处理完才能继续参与返利活动哦~~');
                } else {
                    $this->error('宝子，商家反映您目前有一笔订单存在异常，请联系客服处理完才能继续参与返利活动哦~~');
                }
            } 
        }
        $this->success('满足下单条件');
    }

    /**
     * 报名
     * @param OrderService $orderService
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrder1()
    {
        $is_validate = input('is_validate',0);
        $poiEventId = input('poiEventId', '');
        $address = input('address', '');
        $is_leading = input('is_leading/d', 0); // 是否超前抢单
        $userId = $this->auth->id;
        if ($poiEventId) {
            $play_no = input('id', '');
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
            $error = '您没有饭票，抢单失败';
            if (!$roll) {
                $this->error($error);
            }
            if (isset($_SERVER['HTTP_PLATFORM']) && in_array($_SERVER['HTTP_PLATFORM'], ['wxOfficialAccount','H5'])) {
                $play = Db::name('mtofficial')->where(['no'=>urlencode($play_no)])->order('id DESC')->find();
            } else {
                $play = Db::name('mtofficial')->where(['no'=>$play_no])->order('id DESC')->find();
            }
            if (!$play || !$play['content']) {
                $this->error('活动不存在');
            }
            $content = json_decode($play['content'],1);
            //下单操作
            Db::startTrans();
            try {
                $orderData = [
                    'user_id' => $userId,
                    'shop_no' => $play['no'],
                    'play_no' => $play['no'],
                    'shop_name' => $content['name'],
                    // 'platform_no' => isset($shop_platform['platform_no'])?$shop_platform['platform_no']:'',
                    // 'rebate_amt' => $play['shop_settlement'], // 商户要支付的返点金额
                    // 'service_charge_amt' => $play['service_amt'], // 平台手续费金额
                    'actual_rebate_amt' => $play['back_money'], // 实际用户得到的返点金额
                    'user_pay' => $play['user_pay'], // 满多少
                    'place_time' => time(),
                    'expire_time' => time() + intval(config('sn_expire')),  // 上传单号的过期时间
                    'create_by' => $userId,
                    'location' => $address,
                    'is_yunzhan' => $content['source'],
                    'proposal' => $play['content'],
                ];
                $bwc = new \services\BwcService();
                $res = $bwc->apply($poiEventId,$this->lat,$this->lng,$this->auth->mobile);
                \think\Log::write('活动报名exception1=>'.$res);
                // $res = '{"status":true,"code":200,"message":"success","data":{"order_sn": "M240409193237L45061"}}';
                $decode = json_decode($res,1);
                if ($decode['message']!='success') {
                    $this->error($decode['message']);
                } elseif (!isset($decode['data']['order_sn'])) {
                    $this->error('报名失败');
                } else {
                    $orderData['yunzhan_order_no'] = $decode['data']['order_sn'];
                }
                foreach ($content['plan_list'] as $valuess) {
                    if ($poiEventId==$valuess['plan_id']) {
                        $orderData['crood_type'] = $poiEventId;
                        $orderData['user_pay'] = $valuess['min_amount'];
                        $orderData['rebate_amt'] = $valuess['commission'];
                        $orderData['service_charge_amt'] = config('play.service_amt');
                        $orderData['actual_rebate_amt'] = round($orderData['rebate_amt']-$orderData['service_charge_amt'],2);
                    }
                }
                $order = (new \app\common\model\Order());
                $order->data($orderData)->allowField(true)->save();
                $order['proof'] = [];
                // orderlog
                OrderLog::create([
                    'play_order_id' => $order['id'],
                    // 'play_order_no' => $orderData['yunzhan_order_no'],
                    'create_by' => $this->auth->nickname,
                    'create_by_id' => $userId,
                    'is_front' => 1,
                    'info' => '报名',
                ]);
                // 消耗优惠券
                $res = \app\common\model\UserRollLog::useRoll($roll,$play['no']);
                if (!$res) {
                    Db::rollback();
                    $this->error('消耗优惠券失败');
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                \think\Log::write('活动报名exception=>'.$exception->getMessage());
                $this->error('活动报名失败');
            }
        } else {
            $play_no = input('play_no', '');
            $play = (new \app\admin\model\Play())->where('play_no', $play_no)->find();
            // 是否有大牌专享券
            $play_label = 0;
            $config = config('site.play_label');
            if (count($config)) {
                foreach ($config as $keys => $values) {
                    if ($values=='大牌专享') {
                        $play_label = $keys;
                    }
                }
            }
            $roll = [];
            // 是大牌专享活动就使用大牌专享券，否则使用饭票
            if ($play_label>0 && $play['play_label']==$play_label) {
                $roll = UserRoll::where(['roll_type'=>'card_three','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有大牌专享券，抢单失败';
            } else {
                $roll = UserRoll::where(['roll_type'=>'card_four','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                $error = '您没有饭票，抢单失败';
            }
            if (!$roll) {
                $this->error($error);
            }
            // 是否超前抢单
            $roll2 = [];
            if ($is_leading) {
                // 是否在活动开始前30分钟
                $start_time_str = strtotime(date('Ymd').' '.$play['start_time_str']);
                if (time()<$start_time_str && time()>=$start_time_str-1800) {
                    $roll2 = UserRoll::where(['roll_type'=>'card_one','user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->order('expire_time ASC')->find();
                    if (!$roll2) {
                        $this->error('您没有超前抢单券，抢单失败');
                    }
                } else {
                    $this->error('超前抢单券不可用，抢单失败');
                }
            }
            if (!$is_validate) { // 没有经过validateOder接口验证
                //活动检测
                $user = (new \app\common\model\User())->where(['id'=> $userId,'user_type'=>2,'status'=>'normal'])->find();
                if (!$user) $this->error('该账号暂不能报名');
                if (!$user->mobile) $this->error('请先绑定手机号');

                //活动检测
                if ($user['xzxd']==1 && $play['scheme_no']!=3) {
                    $this->error('无法参与该活动');
                }
                if (empty($play) || $play['stock'] <= 0) $this->error('活动名额已满');
                if ($play['start_date'] > time() || $play['end_date'] < time()) $this->error('不在活动时间内');
                if ($play['play_status'] != 2) $this->error('活动未开始或已完结');

                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'shop_no' => $play['shop_no'],
                    'order_status' => ['in',[1,2,-3,-5]]
                ])->count();
                if ($orderNum) {
                    $this->error('您已经报名过该店铺的活动，请先完成当前未完成的订单');
                }
                // 如果是新用户专享，只能新用户报名
                // $olduser = Db::name('play_order')->where(['user_id'=>$userId,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
                $olduser = order_count_read($userId);
                if ($play['play_label']==2 && $olduser) {
                    $this->error('您不是新用户，不能报名新用户专享活动');
                }
                // 华东师范大学(中山北路校区) 的新用户限制下单
                // if (!$olduser && $address=='华东师范大学(中山北路校区)') {
                //     $this->error('无法参与该活动');
                // }
                // 下单限制
                if ($play['times_limit']==1 && $play['jt']>1 && $play['jc']>0) {
                    // 过去几天
                    $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'shop_no' => $play['shop_no'],
                        'order_status' => ['not in', [-1, -2, -4]],
                        'create_dt' => ['>',$thisday]
                    ])->count();
                    if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
                } elseif ($play['times_limit']==1 && $play['jt']==1 && $play['jc']>0) {
                    // 过去几天
                    $thisday = date('Y-m-d H:i:s',strtotime(date('Ymd'))-($play['jt']-1)*86400);
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'shop_no' => $play['shop_no'],
                        'order_status' => ['not in', [-1, -2, -4]],
                        'create_dt' => ['>',$thisday]
                    ])->count();
                    if ($orderNum >= $play['jc']) $this->error('该活动商家限制'.$play['jt'].'天只能参加'.$play['jc'].'次');
                }
                // 用户完成订单小于6单时，一天最多只能完成2单，用户完成订单大于6单时，一天最多只能完成5单
                $userorder = order_count_read($userId);
                if ($userorder<6) {
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'create_dt' => ['>=',date('Y-m-d',time())],
                        'order_status' => ['not in',[-1,-2,-4]]
                    ])->count();
                    if ($orderNum >= 2) $this->error('您的报名次数已用完');
                } else {
                    $orderNum = (new \app\common\model\Order())->where([
                        'user_id' => $userId,
                        'create_dt' => ['>=',date('Y-m-d',time())],
                        'order_status' => ['not in',[-1,-2,-4]]
                    ])->count();
                    if ($orderNum >= 5) $this->error('您的报名次数已用完');
                }
                // 店铺是否禁止用户下单
                $shop = Db::name('shop')->where(['shop_no'=>$play['shop_no']])->field('limited_user')->find();
                if ($shop['limited_user']) {
                    $limited_user = trim($shop['limited_user'],'|');
                    $limited_user_arr = explode('|', $limited_user);
                    if (count($limited_user_arr) && in_array($this->auth->id, $limited_user_arr)) {
                        $this->error('您已超出该店铺点餐次数上限');
                    }
                }

                // 用户是否存在未完成的异常订单和未完成的不满意反馈订单
                $orderNum = (new \app\common\model\Order())->where([
                    'user_id' => $userId,
                    'order_status' => ['in',[-5,-7,-8]]
                ])->count();
                if ($orderNum) {
                    $this->error('您有未完成的订单，当前不能下单');
                }
            }
            //下单操作
            $orderService = new OrderService();
            $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
            if (Db::name('play_order')->where(['play_order_no'=>$play_order_no])->find()) {
                $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
            }
            $order = $orderService->createOrder($userId, $play, $play_order_no, $userId, $this->auth->nickname,$roll,$roll2,$address);
        }
        if ($order) {$this->success('报名成功', $order);}
        $this->error('报名失败1');
    }

    /**
     * 订单详情
     * @param OrderService $orderService
     */
    public function detail(OrderService $orderService)
    {
        $id = input('id/d', 0);
        $mtofficial = input('mtofficial/d', 0);
        $source = input('source/d', 0);
        // $mtofficial = 1;
        if (!$id) {
            $this->error('缺少必要参数');
        }
        $userId = $this->auth->id;
        $shopObj = new \app\admin\model\Shop();
        $user = Db::name('user')->where('id',$this->auth->id)->field('mobile,entry_mobile')->find();
        if (!$mtofficial) {
            $where['user_id'] = $userId;
            $order = $orderService->getOrderDetail($id, $where);
            if ($order) {
                if ($order['is_yunzhan']==0) {
                    $shop = Db::name('shop')
                        ->field("*")
                        ->where('shop_no',$order['shop_no'])
                        ->find();
                    // $distance_arr = \app\api\service\PlayService::shopDistance($shop,$this->lng,$this->lat,2);
                    $shop_platform = Db::name('shop_platform')->where(['shop_no'=>$order['shop_no']])->field('qrcode_pic,platform_no,is_xls,elm_appenter')->find();
                    if (isset($shop_platform['qrcode_pic']) && $shop_platform['qrcode_pic']) {
                        $shop_platform['qrcode_pic'] = config('upload_domain').$shop_platform['qrcode_pic'];
                    }
                    $shop = array_merge($shop,$shop_platform);
                    // $distance_text = isset($distance_arr[0])?$distance_arr[0]:'0km';
                    $obj = new \app\api\service\PlayService();
                    $distance_text = $obj->get_distance([$this->lat,$this->lng],[$shop['lat'],$shop['lng']]);
                    $distance_text = $distance_text>1000?round($distance_text/1000,2).'km':$distance_text.'m';
                } else {
                    $order['play_order_no'] = $order['yunzhan_order_no'];
                    $content=[];
                    if ($order['proposal']) $content = json_decode($order['proposal'],1);
                    $order['source'] = $content['source'] = $order['is_yunzhan'];
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($order['play_no'],$order['crood_type'],$content);
                    $order['play'] = $play;
                    $order['shop'] = $shop;
                    $distance_text = $play['distance_text'];
                }
                if ($order['order_status']==1 && $order['place_time']>0 && (!isset($order['proof']['wm_order_sn']) || !$order['proof']['wm_order_sn'])) {
                    $order['crood_type'] = '已报名，待下单';
                }elseif ($order['order_status']==1 && $order['place_time']>0 && isset($order['proof']['wm_order_sn']) && $order['proof']['wm_order_sn']) {
                    $order['crood_type'] = '已下单，待反馈';
                }elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                }elseif ($order['order_status']==-5 || $order['order_status']==2) {
                    $order['crood_type'] = '待审核';
                }elseif ($order['order_status']==6) {
                    $order['crood_type'] = '待商家复审';
                }elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                }elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                }elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
            }
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$distance_text,'shop'=>$shop,'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        } else {
            $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
            $order = [];
            $order['shop_no'] = $Mtorder['shop_no'];
            $order['get_coupon'] = $Mtorder['get_coupon'];
            if ($Mtorder['is_yunzhan']==0) {
                $Mtorder = \app\common\model\Mtorder::where('id',$id)->find();
                $order = [];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $content = json_decode($Mtorder['content'],1);
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = [];
                $order['play']['back_money_text'] = isset($content['coupon_text'])?$content['coupon_text']:'';
                $order['play']['img_url'] = $content['picture'];
                $order['play']['shop_name'] = $Mtorder['shop_name'];
                $order['play']['shop_type'] = 1;
                $order['play']['img'] = $content['picture'];
                $order['play']['wxPath'] = isset($content['actionUrl']['wxPath'])?$content['actionUrl']['wxPath']:'';
                $order['play']['wxAppid'] = isset($content['actionUrl']['wxAppid'])?$content['actionUrl']['wxAppid']:'';
                $platform_no = '';
                if (isset($content['actionUrl']['wxPath']) && $content['actionUrl']['wxPath']) {
                    $wxPath = explode('?', $content['actionUrl']['wxPath']);
                    if (isset($wxPath[1]) && $wxPath[1]) {
                        $path = explode('&', $wxPath[1]);
                        foreach ($path as $p) {
                            if (strpos($p,'poi_id=')!==false) {
                                $platform_no = ltrim($p,'poi_id=');
                            }
                            if (strpos($p,'poi_id_str=')!==false) {
                                $platform_no .= '&'.$p;
                            }
                        }
                    }
                }
                $order['planActivityType'] = 1;
                if ($Mtorder['cps_id'] && $content['poiEventId']!=$Mtorder['cps_id'] && isset($content['planActivityInfoList'])) {
                    foreach ($content['planActivityInfoList'] as $valuess) {
                        if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                            $order['planActivityType'] = $valuess['planActivityType'];
                            $content['maxCommission'] = $valuess['maxCommission'];
                            $content['ratio'] = $valuess['ratio'];
                        }
                    }
                }
                // foreach ($content['planActivityInfoList'] as $valuess) {
                //     if ($Mtorder['cps_id']==$valuess['poiEventId']) {
                //         $content['maxCommission'] = $valuess['maxCommission'];
                //         $content['ratio'] = $valuess['ratio'];
                //     }
                // }
                $order['shop'] = [];
                $order['shop']['shop_name'] = $content['name'];
                $order['shop']['platform_no'] = $platform_no;
                $order['shop']['shop_type_text'] = '美团';
                $order['shop']['logo_pic_url'] = $content['picture'];
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['place_time']>0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==3) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['place_time']>0 && isset($content2['code']) && $content2['code']==4) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    $order['crood_type'] = '已下单';
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $ratio = normal_return($content['maxCommission'],$content['ratio'])*100;
                $order['ratio'] = $ratio;
                $order['maxCommission'] = max_return($content['maxCommission'],$content['ratio']);
                $order['mobile'] = $Mtorder['proposal'];
                if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['deliveryDistance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);   
            } elseif (in_array($Mtorder['is_yunzhan'], [4,5])) {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->newmtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $content['distance'] = $play['distance_text'];
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                if ($Mtorder['is_yunzhan']==4)  $order['shop_no'] = $Mtorder['crood_type'];
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['scheme_no']-1;
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
                if ($Mtorder['is_yunzhan']==5) {
                    $order['elmorder_num'] = Db::name('mtofficial_order')->where(['user_id'=>$this->auth->id,'order_status'=>3,'is_yunzhan'=>5])->count();
                }
            } else {
                $content=isset($Mtorder['content'])?json_decode($Mtorder['content'],1):[];
                $order['source'] = $content['source'] = $Mtorder['is_yunzhan'];
                list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($Mtorder['play_no'],$Mtorder['cps_id'],$content);
                $order['mtofficial'] = 1;
                $order['id'] = $Mtorder['id'];
                $order['play_order_no'] = $Mtorder['play_order_no'];
                $order['shop_name'] = $Mtorder['shop_name'];
                $order['place_time'] = $Mtorder['place_time'];
                $order['expire_time'] = $Mtorder['expire_time'];
                $order['expire_time_text'] = date('Y/m/d H:i',$Mtorder['expire_time']);
                $order['create_dt'] = $Mtorder['create_dt'];
                $order['order_status'] = $Mtorder['order_status'];
                // $mtofficial = Db::name('mtofficial')->where(['no'=>$Mtorder['play_no']])->order('id DESC')->find();
                $order['pay_time'] = '';
                $order['user_pay'] = 0;
                $order['actual_rebate_amt'] = 0;
                if ($Mtorder['user_pay']!=0) {
                    $order['pay_time'] = date('Y/m/d H:i:s',$Mtorder['pay_time']);
                    $order['user_pay'] = $Mtorder['user_pay'];
                    $order['actual_rebate_amt'] = $Mtorder['actual_rebate_amt'];
                }
                $order['play'] = $play;
                $order['planActivityType'] = $play['planActivityType'];
                $order['shop'] = $shop;
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                $order['proof'] = ['wm_order_sn'=>'','handle_admin_desc'=>''];
                if ($Mtorder['content']) {
                    $content2 = json_decode($Mtorder['content'],1);
                }
                if ($order['order_status']==1 && $order['pay_time']==0) {
                    $order['crood_type'] = '已报名，待下单';
                } elseif ($order['order_status']==1 && $order['pay_time']>0) {
                    $order['crood_type'] = '已下单，待反馈';
                } elseif ($order['order_status']==4 || $order['order_status']==-5) {
                    if ($order['planActivityType']==1) {
                        $order['crood_type'] = '已下单，待评价';
                    } else {
                        $order['crood_type'] = '已下单，待完成';
                    }
                } elseif ($order['order_status']==-2) {
                    $order['crood_type'] = '超时取消，订单关闭';
                } elseif ($order['order_status']==-1 || $order['order_status']==-4) {
                    $order['crood_type'] = '已取消';
                } elseif ($order['order_status']==-3) {
                    $order['crood_type'] = '已驳回';
                } elseif ($order['order_status']==-6 || $order['order_status']==-7 || $order['order_status']==3) {
                    $order['crood_type'] = '已完成';
                }
                $order['place_time_text'] = date('m/d H:i',$order['place_time']);
                // 驳回原因
                if ($order['proof']['handle_admin_desc']) {
                    $explode = explode('（', $order['proof']['handle_admin_desc']);
                    if (isset($explode[1]) && $explode[1]) {
                        $explode = explode('）', $explode[1]);
                    }
                    if (isset($explode[0])) {
                        $order['proof']['handle_admin_desc'] = $explode[0];
                    }
                }
                $order['ratio'] = $play['ratio'];
                $order['maxCommission'] = $play['maxCommission'];
            }
            $order['mobile'] = $Mtorder['proposal'];
            if ($order) $this->success('订单详情', ['order'=>$order,'distance_text'=>$content['distance'],'shop'=>$order['shop'],'orderNum'=>empty($userId)?0:order_count_read($userId)]);
        }
        $this->error('订单信息获取失败');
    }

    /**
     * 提交证明
     * @param OrderService $orderService
     */
    public function proof(OrderService $orderService)
    {
        $three_image = input('img3', '');
        if (!$three_image) $this->error('请上传用餐评价截图');
        $shop_type = input('shop_type', ''); 
        $shop_no = input('shop_no', ''); 
        if (!$shop_type || !$shop_no) $this->error('缺少必要参数');
        if (!in_array($shop_type, ['美团','饿了么','京东'])) $this->error('参数有误');
        if ($shop_type=='美团') {
            $shop_authorize = Db::name('shop_authorize')->where(['shop_no'=>$shop_no,'is_success'=>1])->find();
        } else {
            $shop_authorize = Db::name('shop')->where('shop_no',$shop_no)->find();
        }
        if (!$shop_authorize) $this->error('店铺信息有误');
        //外卖单号
        $wm_order_sn = input('wm_order_sn', '','htmlspecialchars,htmlentities');
        $wm_order_sn = trim($wm_order_sn);
        $wm_order_sn = str_replace(' ', '', $wm_order_sn);  // 当前平台订单id
        if (!$wm_order_sn) {
            $this->error('请上传正确单号');
        }
        if (in_array($shop_type, ['美团','饿了么']) && (!is_numeric($wm_order_sn) || !\think\Validate::is($wm_order_sn, '\S{18,30}'))) {
            $this->error('单号格式不对');
        }
        // 同一订单号提交过后不可重复提交
        $snNUm = OrderModel::where([
            'wm_order_sn'=>$wm_order_sn,
            'order_status' => ['in',[1,2,3,-3,-5,-6,-7,-8,-9]]
        ])->find();
        if (count($snNUm)>0) {
            $this->error('该外卖单号已使用过');
        }
        $userId = $this->auth->id;
        $orderNum = (new \app\common\model\Order())->where([
            'user_id' => $userId,
            'create_dt' => ['>=',date('Y-m-d',time())],
            'order_status' => ['in',[3,-7,-8,-9]]
        ])->count();
        if ($orderNum > 10) $this->error('超过正常下单次数');
        // 用户下过多少单
        $hasOrder = order_count_read($userId);
        // if ($hasOrder>99) $this->error('您的报名次数已用完');
        $order = new OrderModel();
        $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
        if (Db::name('play_order')->where(['play_order_no'=>$play_order_no])->find()) {
            $play_order_no = $this->generateNo(['biz_tag'=>'play_order_no','len'=>12,'int_prefix'=>6]);
        }
        $shop = Db::name('shop')->field("*")->where('shop_no',$shop_no)->find();
        $service_admin_by = Db::name('admin')->where('id',$shop['salesman_admin_id'])->value('nickname');
        if (!$service_admin_by) $service_admin_by='';
        $orderData = [
            'user_id' => $userId,
            'shop_no' => $shop_authorize['shop_no'],
            'shop_name' => $shop_authorize['shop_name'],
            'place_time' => time(),
            'expire_time' => time() + intval(config('sn_expire')),  // 上传单号的过期时间
            'create_by' => $userId,
            'play_order_no' => $play_order_no,
            'platform_no' => $shop_authorize['shop_type'],
            'service_admin_by' => $service_admin_by,
            'service_admin_id' => $shop['salesman_admin_id'],
        ];
        // 最新订单返利机制
        $orderData['rebate_amt'] = floatval($shop['shop_settlement']);
        $shop_back_money = json_decode($shop['back_money'],1);
        foreach ($shop_back_money as $key => $value) {
            if ($hasOrder<intval($key)) {
                $orderData['actual_rebate_amt'] = $value;
                break;
            }
        }
        // $order_num = order_count_read($userId);
        // if ($order_num==0) { // 第一单：3.88
        //     $orderData['actual_rebate_amt'] = 3.88;
        // } elseif ($order_num<2) { // 第二：0.88
        //     $orderData['actual_rebate_amt'] = 0.88;
        // } else { // 第四单及以上：0.18
        //     $orderData['actual_rebate_amt'] = 0.18;
        // }
        $orderData['service_charge_amt'] = round($orderData['rebate_amt']-$orderData['actual_rebate_amt'],2);
        $proof = new OrderProof();
        Db::startTrans();
        try {
            $is_dissatisfied = 0;
            // 提交渠道：1-H5，2-在线识别3-APP人工通道
            $data['platform'] = 0;
            if ($_SERVER['HTTP_PLATFORM']=='wxOfficialAccount') {
                $data['platform'] = 1;
            } elseif ($_SERVER['HTTP_PLATFORM']=='wxMiniProgram') {
                $data['platform'] = 4;
            } elseif ($_SERVER['HTTP_PLATFORM']=='App') {
                if ($data['one_image'] && $data['two_image']) { // 上传前两张图的是人工提交
                    $data['platform'] = 3;
                } elseif (in_array($proof['machine_audit_state'], [2,3])) {
                    $data['platform'] = 2;
                } else {
                    $data['platform'] = 3;
                }
            } 
            // 机审接口
            $data['machine_audit_state'] = -1;
            $User = new \app\common\model\User();
            $user = $User->get($userId);
            $resarr = ['订单状态'=>0,'订单号'=>0,'下单时间'=>0,'店铺名称'=>0,'反馈识别'=>0];
            // 先判断反馈截图里是否有店铺名称
            $ocr = new \services\BaiduocrService(); // 创建对象
            $ocrdata = $ocr->ocr(config('upload_domain').$three_image); // 调用对象开放的函数
            if (!isset($ocrdata['content'])) { // 识别成功
                $this->error('图片识别出错');
            }
            if (!$ocrdata['content']) $this->error('评价截图不符合示例图要求');
            $content = str_replace(' ', '', $ocrdata['content']);
            $content = str_replace('（', '', $content);
            $content = str_replace('(', '', $content);
            $content = str_replace('）', '', $content);
            $content = str_replace(')', '', $content);
            $content = str_replace('：', ':', $content);
            $content = str_replace('！', '', $content);
            $content = str_replace('!', '', $content);
            // $content =  str_replace('.', '', $content);
            $content =  str_replace('·', '.', $content);
            $content =  str_replace('•', '.', $content);
            $content =  str_replace('●', '.', $content);
            $content =  str_replace('¥', '￥', $content);
            $content = match_dot($content);
            if (strpos($content, '.')) {
                $content = match_dot($content);
            }
            \think\Log::write($wm_order_sn.'ocr识别文字：',$content);
            $logtext = '';
            if (isset($content) && $content) {
                // 识别店铺名称
                $shop_name =  str_replace('（', '', $shop_authorize['shop_name']);
                $shop_name =  str_replace('(', '', $shop_name);
                $shop_name =  str_replace('）', '', $shop_name);
                $shop_name =  str_replace(')', '', $shop_name);
                $shop_name =  str_replace(' ', '', $shop_name);
                $shop_name =  str_replace('！', '', $shop_name);
                $shop_name =  str_replace('!', '', $shop_name);
                // $shop_name =  str_replace('.', '', $shop_name);
                $shop_name =  str_replace('·', '.', $shop_name);
                $shop_name =  str_replace('・', '.', $shop_name);
                $shop_name =  str_replace('•', '.', $shop_name);
                $shop_name =  str_replace('●', '.', $shop_name);
                $shop_name =  str_replace('.', '', $shop_name);
                // 识别评价：是否有两个5星
                if ($shop_type=='美团') {
                    if (!strpos($content,'4星') && !strpos($content,'3星') && !strpos($content,'2星') && !strpos($content,'1星')) {
                        // 反馈识别还需要确定店铺名称和日期
                        $shop_name = mb_substr($shop_name, 0,6);
                        // if (strpos($content,$shop_name)!==false) {
                            $resarr['店铺名称'] = 1;
                        // }
                        // if (strpos($content,$shop_name)===false) {
                        //     $this->error('用餐评价截图中的店铺名称不匹配');
                        // }
                        // $date = date('Y-m-d',$orderData['place_time']);
                        // $date2 = date('Y.m.d',$orderData['place_time']);
                        // $date3 = date('Y-m-d',($orderData['place_time']+86400));
                        // $date4 = date('Y.m.d',($orderData['place_time']+86400));
                        // if ((strpos($content,$date) || strpos($content,$date2) || strpos($content,$date3) || strpos($content,$date4) || strpos($content,'今天') || strpos($content,'刚刚') || strpos($content,'分钟前') || strpos($content,'小时前'))) {} else {
                        //     $this->error('评价截图时间有误');
                        // }
                        $noarr = explode('5星', $content);
                        $logtext .= '，反馈识别：'.count($noarr);
                        if (count($noarr)>=3) {
                            $resarr['反馈识别'] = 1;
                        }
                        // 识别评价：是否有两个5星
                        if (!isset($resarr['反馈识别'])) {
                            $noarr = explode('非常满意', $content);
                            $logtext .= '，反馈识别非常满意：'.count($noarr);
                            if (count($noarr)>=2) {
                                $resarr['反馈识别'] = 1;
                            }
                        }
                        \think\Log::write($wm_order_sn.'ocr识别结果：'.$logtext);
                    }
                } else {
                    if (!strpos($content,'4星') && !strpos($content,'3星') && !strpos($content,'2星') && !strpos($content,'1星')) {
                        // 反馈识别还需要确定店铺名称和日期
                        $shop_name = mb_substr($shop_name, 0,6);
                        $logtext .= '，反馈识别店铺：'.$shop_name;
                        // if (strpos($content,$shop_name)!==false) {
                            $resarr['店铺名称'] = 1;
                        // }
                        // if (strpos($content,$shop_name)===false) {
                        //     $this->error('用餐评价截图中的店铺名称不匹配');
                        // }
                        // $date = date('Y-m-d',$orderData['place_time']);
                        // $date2 = date('Y.m.d',$orderData['place_time']);
                        // $date3 = date('Y-m-d',($orderData['place_time']+86400));
                        // $date4 = date('Y.m.d',($orderData['place_time']+86400));
                        // if ((strpos($content,$date) || strpos($content,$date2) || strpos($content,$date3) || strpos($content,$date4) || strpos($content,'刚刚') || strpos($content,'分钟前') || strpos($content,'小时前'))) {} else {
                        //     $this->error('评价截图时间有误');
                        // }
                        $noarr = explode('5星', $content);
                        $logtext .= '，反馈识别：'.count($noarr);
                        if (count($noarr)>=3) {
                            $resarr['反馈识别'] = 1;
                        }
                        if (!isset($resarr['反馈识别'])) {
                            $noarr = explode('满意度超赞包装超赞味道超赞', $content);
                            $logtext .= '，反馈识别满意度超赞包装超赞味道超赞：'.count($noarr);
                            if (count($noarr)>=2) {
                                $resarr['反馈识别'] = 1;
                            }
                        }
                        if (!isset($resarr['反馈识别'])) {
                            $noarr = explode('超赞', $content);
                            $logtext .= '，反馈识别超赞：'.count($noarr);
                            if (count($noarr)>=3) {
                                $resarr['反馈识别'] = 1;
                            }
                        }
                        \think\Log::write($wm_order_sn.'ocr识别结果：'.$logtext);
                    }
                }
                // 评价截图只要包含了 满意，5星，口味，包装，配送，评价等词语(或的关系)都过掉
                if (!$resarr['反馈识别']) {
                    if (strpos($content,'满意')!==false || strpos($content,'5星')!==false || strpos($content,'口味')!==false || strpos($content,'包装')!==false || strpos($content,'配送')!==false || strpos($content,'评价')!==false) {
                        $resarr['反馈识别'] = 1;
                    } else {
                        $this->error('提交失败，反馈截图不符合要求');
                    }
                }
            }
            if ($shop_type=='美团') {
                // 订单是否完成
                $MeishikaiService = new \services\MeishikaiService();
                $meishikai = Db::name('meishikai')->where('id',1)->find();
                $res = $MeishikaiService->getOrderDetails($meishikai['token'],$shop_type,$shop_authorize['pshopid'],$wm_order_sn);
                $decode = json_decode($res,1);
                if (!isset($decode['IsSuccess']) || !$decode['IsSuccess']) {
                    \think\Log::write($wm_order_sn.'店铺名称与外卖单号不匹配exception=>'.$res);
                    if (!isset($decode['Message']) || $decode['Message']!='账号不存在或已过期') {
                        $this->error('接口请求有误');
                    }
                    $res2 = $MeishikaiService->userLogin();
                    $decode2 = json_decode($res2,1);
                    if (!isset($decode2['Content']['Token']) || !$decode2['Content']['Token']) {
                        $this->error('获取token参数失败');
                    }
                    Db::name('meishikai')->where('id',1)->update([
                        'content' => $res2,
                        'token' => $decode2['Content']['Token'],
                        'update_dt' => date('Y-m-d H:i:s'),
                        // 'expire_time' => strtotime($decode['Content']['DatExpired']),
                        'expire_time' => time()+518400,
                    ]);
                    $meishikai['token'] = $decode2['Content']['Token'];
                    $res = $MeishikaiService->getOrderDetails($meishikai['token'],$shop_type,$shop_authorize['pshopid'],$wm_order_sn);
                    $decode = json_decode($res,1);
                    if (!isset($decode['IsSuccess']) || !$decode['IsSuccess']) {
                        \think\Log::write($wm_order_sn.'店铺名称与外卖单号不匹配exception=>'.$res);
                        $this->error('接口请求有误');
                    }
                }
                if (isset($decode['Content']['status']) && $decode['Content']['status']==8) {
                    $resarr['订单状态'] = 1;
                    $resarr['订单号'] = 1;
                    $resarr['店铺名称'] = 1;
                } else {
                    $this->error('店铺名称选择错误，请您重新搜索并选择正确的店铺名称后再提交');
                }
                $data['actual_pay'] = $decode['Content']['total'];
                $orderData['place_time'] = $decode['Content']['orderSendTime'];
                $shop_type_int = 1;
            } elseif ($shop_type=='饿了么') {
                $ElemService = new \services\ElemService('');
                $res = $ElemService->check($wm_order_sn);
                $decode = json_decode($res,1);
                if (!isset($decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['biz_error_code']) || $decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['biz_error_code']!=0) {
                    $this->error($decode['error_response']['sub_msg']);
                }
                // 是否完成订单
                if (isset($decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['data']['order_info']['finish_time'])) {
                    $timestap = strtotime($decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['data']['order_info']['finish_time']);
                    if ($timestap) {
                        $resarr['订单状态'] = 1;
                        $resarr['订单号'] = 1;
                    } else {
                        $this->error('店铺名称选择错误，请您重新搜索并选择正确的店铺名称后再提交');
                    }
                }
                // 店铺名称
                if (isset($decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['data']['order_info']['shop_name'])) {
                    $shop_name = $decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['data']['order_info']['shop_name'];
                    $img_shop_name = $shop_name;
                    $shop_name =  str_replace('（', '', $shop_name);
                    $shop_name =  str_replace('(', '', $shop_name);
                    $shop_name =  str_replace('）', '', $shop_name);
                    $shop_name =  str_replace(')', '', $shop_name);
                    $shop_name =  str_replace(' ', '', $shop_name);
                    $shop_name =  str_replace('！', '', $shop_name);
                    $shop_name =  str_replace('!', '', $shop_name);
                    // $shop_name =  str_replace('.', '', $shop_name);
                    $shop_name =  str_replace('·', '.', $shop_name);
                    $shop_name =  str_replace('・', '.', $shop_name);
                    $shop_name =  str_replace('•', '.', $shop_name);
                    $shop_name =  str_replace('●', '.', $shop_name);
                    $shop_name =  str_replace('.', '', $shop_name);

                    $shop_name2 =  str_replace('（', '', $shop_authorize['shop_name']);
                    $shop_name2 =  str_replace('(', '', $shop_name2);
                    $shop_name2 =  str_replace('）', '', $shop_name2);
                    $shop_name2 =  str_replace(')', '', $shop_name2);
                    $shop_name2 =  str_replace(' ', '', $shop_name2);
                    $shop_name2 =  str_replace('！', '', $shop_name2);
                    $shop_name2 =  str_replace('!', '', $shop_name2);
                    // $shop_name2 =  str_replace('.', '', $shop_name2);
                    $shop_name2 =  str_replace('·', '.', $shop_name2);
                    $shop_name2 =  str_replace('・', '.', $shop_name2);
                    $shop_name2 =  str_replace('•', '.', $shop_name2);
                    $shop_name2 =  str_replace('●', '.', $shop_name2);
                    $shop_name2 =  str_replace('.', '', $shop_name2);
                    if ($shop_name==$shop_name2) {
                        $resarr['店铺名称'] = 1;
                    } else {
                        // $resarr['店铺名称'] = 0;
                        $this->error('店铺名称选择错误，请您重新搜索并选择正确的店铺名称后再提交');
                    }
                }
                $data['actual_pay'] = 0;
                $orderData['place_time'] = strtotime($decode['alibaba_alsc_union_eleme_tool_order_attrbute_check_response']['data']['order_info']['create_time']);
                $shop_type_int = 2;
            } else {
                $shop_type_int = 3;
                $data['actual_pay'] = 0;
            }
            // 是否是今天下单
            if (isset($orderData['place_time'])) {
                $timestap = time()-$orderData['place_time'];
                if ($timestap<259200 && $timestap>=0) {
                    $resarr['下单时间'] = 1;
                } else {
                    $this->error('订单超过72小时');
                }
            }
            if ($shop_type=='美团' || $shop_type=='饿了么') {
                // 生成图片
                $mb_strlen = mb_strlen($shop_authorize['shop_name']);
                if ($mb_strlen>14) {
                    $shop_name = mb_substr($shop_authorize['shop_name'],0,14).'...';
                    $x = 175;
                } else {
                    $shop_name = $shop_authorize['shop_name'];
                    $x = (14-$mb_strlen)*10+175+10;
                }
                $img_actual_pay = $data['actual_pay'];
                if ($img_actual_pay==0) $img_actual_pay='-';
                $arr = [
                    [$shop_name,$x,443],
                    [$wm_order_sn,205,475],
                    [date('Y-m-d H:i:s',$orderData['place_time']),226,507],
                    [$img_actual_pay,320,539],
                ];
                $resimg = $orderService->buildImg($arr,$shop_type_int);
                if ($resimg) {
                    $data['one_image'] = $resimg;
                    $data['two_image'] = $data['one_image'];
                }
            } else {
                $data['one_image'] = $data['two_image'] = '';
            }
            $data['machine_audit_state'] = 1;
            foreach ($resarr as $key => $value) {
                if ($value!=1) {
                    $data['machine_audit_state'] = -1;
                }
            }
            $data['machine_audit_desc'] = json_encode($resarr,JSON_UNESCAPED_UNICODE);
            // 机审通过，则订单已完成
            if ($data['machine_audit_state']==1) {
                // 订单状态
                $orderData['order_status'] = 3;
                $orderData['update_by'] = $this->auth->id;
                $orderData['wm_order_sn'] = $wm_order_sn;
                if ($user['is_limited']) {
                    $orderData['actual_rebate_amt'] = 0.18;//被限制的用户每次提交返现只返0.18元
                    $orderData['service_charge_amt'] = round($orderData['rebate_amt']-$orderData['actual_rebate_amt'],2);
                }
                $orderData['amount'] = $hasOrder+1;
                $order->data($orderData)->allowField(true)->save();
                //
                $data['handle_status'] = 1;
                $data['three_image'] = $three_image;
                $data['wm_order_sn'] = $wm_order_sn;
                $data['play_order_no'] = $orderData['play_order_no'];
                $data['shop_no'] = $orderData['shop_no'];
                $data['handle_time'] = time();
                $data['upload_time'] = time();
                // 如果识别出来是4星，3星，2星，1星。这笔订单还是自动给用户派发红包，但是不进入商家账单。
                if ($resarr['反馈识别']!=1) $orderData['order_status'] = -6;
                $proof->save($data);
                OrderLog::create([
                    'play_order_id' => $order->id,
                    'play_order_no' => $order->play_order_no,
                    'info' => '机审通过',
                    'create_by' => $this->auth->nickname,
                    'create_by_id' => $this->auth->id,
                    'is_front' => 1,
                ]);
                // 用户获得吃豆
                $beans = $order['actual_rebate_amt'];
                if ($user['is_limited']) $beans = 0.18;//被限制的用户每次提交返现只返0.18元
                $User->beans($beans,$order['user_id'],'下单返豆',$order['play_order_no']);
                // 返豆
                // \fast\Http::sendAsyncRequest(config('domain').'/index/index/distributeBeans?no='.$order['play_order_no'],[],'GET');
            } else {
                $data['upload_time'] = time();
                $data['three_image'] = $three_image;
                $data['wm_order_sn'] = $wm_order_sn;
                $data['play_order_no'] = $orderData['play_order_no'];
                $data['shop_no'] = $orderData['shop_no'];
                $data['user_id'] = $userId;
                $proof->save($data);
                $info = '提交凭据';
                $orderData['order_status'] = 2;
                $orderData['wm_order_sn'] = $wm_order_sn;
                if ($user['is_limited']) {
                    $orderData['actual_rebate_amt'] = 0.18;//被限制的用户每次提交返现只返0.18元
                    $orderData['service_charge_amt'] = round($orderData['rebate_amt']-$orderData['actual_rebate_amt'],2);
                }
                $order->data($orderData)->allowField(true)->save();
                // orderlog
                \app\common\model\OrderLog::create([
                    'play_order_id' => $order['id'],
                    'play_order_no' => $order['play_order_no'],
                    'create_by' => $this->auth->nickname,
                    'create_by_id' => $userId,
                    'is_front' => 1,
                    'info' => $info,
                ]);
            }
            Db::commit(); 
            // 提现
            if ($data['machine_audit_state']==1) {
                file_get_contents(config('domain').'/index/index/distributeBeans?no='.$order['play_order_no']);
            }
        } catch (Exception $exception) {
            Db::rollback();
            \think\Log::write('提交活动凭据exception=>'.$exception->getMessage());
            $this->error($exception->getMessage());
        }
        $this->success('提交成功，等待审核');
    }

    public function cancel()
    {
        $play_order_no = input('play_order_no','');
        $order = (new \app\common\model\Order())->where([
            'play_order_no' => $play_order_no,
        ])->find();
        if (empty($order)) $this->error('不可取消');
        if ($order['order_status']!=6) $this->error('不可取消');
        $order->order_status = -1;
        $order->save();


        // orderlog
        \app\common\model\OrderLog::create([
            'play_order_id' => $order['id'],
            'play_order_no' => $play_order_no,
            'create_by' => 'chbc',
            'create_by_id' => 0,
            'is_front' => 1,
            'info' => '取消订单',
        ]);
        $this->success('取消成功');
    }


    public function shopList()
    {
        $shop_name = input('shop_name','');
        $shop_type = input('shop_type','');
        if ($shop_name) {
            if ($shop_type=='美团') {
                $shop_type = 1;
                $shops = Db::name('shop')->where('shop_status=1 and is_auth=1 and shop_type='.$shop_type.' and shop_name like "%'.$shop_name.'%"')->field('id,shop_name,shop_no')->limit(5)->select();
            } elseif ($shop_type=='饿了么') {
                $shop_type = 2;
                $shops = Db::name('shop')->where('shop_status=1 and is_auth=1 and shop_type='.$shop_type.' and shop_name like "%'.$shop_name.'%"')->field('id,shop_name,shop_no')->limit(5)->select();
            } else {
                $shop_type = 3;
                $shops = Db::name('shop')->where('shop_status=1 and is_auth=1 and shop_type='.$shop_type.' and shop_name like "%'.$shop_name.'%"')->field('id,shop_name,shop_no')->limit(5)->select();
            }
            $this->success('success',$shops);
        }
    }
}